package com.zyt.aop;

import com.zyt.mapper.OperateLogMapper;
import com.zyt.pojo.OperateLog;
import com.zyt.utils.CurrentHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;
@Slf4j
@Aspect
@Component
public class OperateLogAspect {

    @Autowired
    private OperateLogMapper operateLogMapper;

    // 假设当前用户ID可以从 ThreadLocal 或 SecurityContext 获取
    private Integer getCurrentEmpId() {
        // 示例：从 Spring Security 获取或自定义上下文获取
        return CurrentHolder.getCurrentId(); // 这里应替换为实际逻辑
    }

    @Around("@annotation(com.zyt.anno.Log)")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();

        // 获取方法执行所需信息
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();

        Object result = null;
        try {
            result = joinPoint.proceed(); // 执行目标方法
        } catch (Exception e) {
            throw e;
        } finally {
            long costTime = System.currentTimeMillis() - startTime;

            // 构建日志对象
            OperateLog olog = new OperateLog();
            olog.setOperateEmpId(getCurrentEmpId());
            olog.setOperateTime(LocalDateTime.now());
            olog.setClassName(className);
            olog.setMethodName(methodName);
            olog.setMethodParams(Arrays.toString(args));
            olog.setReturnValue(result != null ? result.toString() : null);
            olog.setCostTime(costTime);

            // 插入日志
            log.info("记录操作日志:{}",olog);
            operateLogMapper.insert(olog);
        }

        return result;
    }
}